package org.exhaust.framework.net.common.protocol.decoder.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.exhaust.framework.net.common.protocol.BaseFrame;
import org.exhaust.framework.net.common.protocol.decoder.ByteBufDecoderHelper;
import org.exhaust.framework.net.common.protocol.handler.BusinessDataHandler;

import java.util.List;

/**
 * 对象本身作为Handler添加到Pipeline中时，每个对象都要New
 * 如果ByteBufDecoderHelper有状态，譬如使用了类似ReplayingDecoder的机制，需要在pipeline中每次都new一个，如果无状态，可以共用一个
 * BusinessDataHandler可以共享
 */
public class NoneSharableTcpByteBufDecoder<T extends BaseFrame> extends ByteToMessageDecoder {
    private BusinessDataHandler<T> handler;

    private ByteBufDecoderHelper<T> decoderHelper;

    public NoneSharableTcpByteBufDecoder(ByteBufDecoderHelper<T> decoderHelper, BusinessDataHandler<T> handler) {
        this.decoderHelper = decoderHelper;
        this.handler = handler;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        T decoded = decode(ctx, in);
        if (decoded != null) {
            this.handler.receiveMsg(ctx, decoded);
        }
    }

    protected T decode(ChannelHandlerContext ctx, ByteBuf in) {
        return decoderHelper.decode(ctx, in);
    }
}
